﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TMDT_Nhom1A.BUS;
using TMDT_Nhom1A.DTO;

namespace TMDT_Nhom1A
{
    public partial class ThongTinGioHang : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                ConnectData();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ConnectData();
        }

        public void ConnectData()
        {
            Cart cart = (Cart)Session["Cart"];
            if (Session["Role"].ToString() == "")
            {
                if (Request.Cookies["Cart"] != null && !string.IsNullOrEmpty(Request.Cookies["Cart"].Value) && Session["Flag"].ToString() == "0")
                {
                    cart = new Cart();
                    cart.AddToCart(MyCookie.ReadCookie(Request.Cookies["Cart"].Value.ToString()));
                    Cart carttemp = (Cart)Session["Cart"];
                    for (int i = 0; i < carttemp.GetList().Count; i++)
                    {
                        cart.AddToCart(carttemp.GetList()[i]);
                    }
                    Session["Cart"] = cart;

                    Session["Flag"] = 1;
                }
            }
            else
            {
                if (Request.Cookies["Cart"] != null && !string.IsNullOrEmpty(Request.Cookies["Cart"].Value) && Session["Flag"].ToString() == "0")
                {
                    cart = new Cart();
                    cart.AddToCart(MyCookie.ReadCookie(Request.Cookies["Cart"].Value.ToString()));
                    Cart carttemp = (Cart)Session["Cart"];
                    for (int i = 0; i < carttemp.GetList().Count; i++)
                    {
                        cart.AddToCart(carttemp.GetList()[i]);
                    }
                    Session["Cart"] = cart;
                    Session["Flag"] = 1;
                }
                if ((Request.Cookies["Cart"] == null && Session["Flag"].ToString() == "0") || Session["Flag"].ToString() == "1")
                {
                    cart = (Cart)Session["Cart"];
                    Cart carttemp = OrderB2B_BUS.GetSaveDetailOrderB2B(Session["UserID"].ToString());
                    Cart cartnew = new Cart();
                    for (int i = 0; i < carttemp.GetList().Count; i++)
                    {
                        cartnew.AddToCart(carttemp.GetList()[i]);
                    }
                    for (int i = 0; i < cart.GetList().Count; i++)
                    {
                        cartnew.AddToCart(cart.GetList()[i]);
                    }
                    Session["Cart"] = cartnew;
                    Session["Flag"] = 2;
                }

                
            }
            cart = (Cart)Session["Cart"];
            Session["TotalPrice"] = cart.CalulateTotalPrice();
            lbthanhtien.Text = Session["TotalPrice"].ToString();
            gvdetailorderproduct.DataSource = cart.GetList();
            gvdetailorderproduct.DataBind();
        }

        protected void gvdetailorderproduct_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CheckAll")
            {
                CheckBox cbcheckall = (CheckBox)gvdetailorderproduct.HeaderRow.FindControl("cbCheckAll");
                if (cbcheckall.Checked == true)
                {
                    for (int i = 0; i < gvdetailorderproduct.Rows.Count; i++)
                    {
                        CheckBox cbcheck = (CheckBox)gvdetailorderproduct.Rows[i].FindControl("cbcheck");
                        cbcheck.Checked = false;
                        cbcheckall.Checked = false;
                    }
                }
                else
                {
                    for (int i = 0; i < gvdetailorderproduct.Rows.Count; i++)
                    {
                        CheckBox cbcheck = (CheckBox)gvdetailorderproduct.Rows[i].FindControl("cbcheck");
                        cbcheck.Checked = true;
                        cbcheckall.Checked = true;
                    }
                }
            }
            if (e.CommandName == "btDelete")
            {
                Cart cart = (Cart)Session["Cart"];
                for (int i = cart.GetList().Count - 1; i >= 0; i--)
                {
                    string temp = cart.GetList()[i].ElectricDeviceID;
                    if (e.CommandArgument.ToString() == cart.GetList()[i].ElectricDeviceID)
                    {
                        cart.RemoveOrderProductOutCart(i);
                    }
                }
                Session["TotalPrice"] = cart.CalulateTotalPrice();
                lbthanhtien.Text = Session["Cart"].ToString();
                ConnectData();
            }
            if (e.CommandName == "btDeleteAll")
            {
                Cart cart = (Cart)Session["Cart"];
                for (int i = cart.GetList().Count - 1; i >= 0; i--)
                {
                    CheckBox cbcheck = (CheckBox)gvdetailorderproduct.Rows[i].FindControl("cbcheck");
                    if (cbcheck.Checked == true)
                    {
                        cart.RemoveOrderProductOutCart(i);
                    }
                }
                Session["TotalPrice"] = cart.CalulateTotalPrice();
                lbthanhtien.Text = Session["Cart"].ToString();
                ConnectData();

            }
        }

        protected void gvdetailorderproduct_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lbPriceCoupon = (Label)e.Row.FindControl("lbPriceCoupon");
                if (decimal.Parse(lbPriceCoupon.Text) != 0)
                {
                    lbPriceCoupon.Visible = true;
                    e.Row.FindControl("delRetailPrice").Visible = true;
                    e.Row.FindControl("delDealerPrice").Visible = true;
                    e.Row.FindControl("lbRetailPrice").Visible = false;
                    e.Row.FindControl("lbDealerPrice").Visible = false;
                }
                else
                {
                    e.Row.FindControl("lbinfor").Visible = true;
                }
            }
        }

        protected void gvdetailorderproduct_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvdetailorderproduct.EditIndex = e.NewEditIndex;
            ConnectData();
        }

        protected void gvdetailorderproduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvdetailorderproduct.EditIndex = -1;
            ConnectData();
        }

        protected void gvdetailorderproduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Cart cart = (Cart)Session["Cart"];
            TextBox quantity = (TextBox)gvdetailorderproduct.Rows[e.RowIndex].Cells[4].Controls[0];
            cart.UpdateCart(e.RowIndex, int.Parse(quantity.Text.ToString()));

            gvdetailorderproduct.EditIndex = -1;
            Session["TotalPrice"] = cart.CalulateTotalPrice();
            lbthanhtien.Text = Session["TotalPrice"].ToString();
            ConnectData();
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            Cart cart = (Cart)Session["Cart"];
            if (Session["Role"].ToString() == "Đối tác doanh nghiệp")
            {
                ORDER_B2B orderb2b = new ORDER_B2B();
                orderb2b.UserID = int.Parse(Session["UserID"].ToString());
                orderb2b.OrderedDate = DateTime.Now;
                orderb2b.TotalPrice = decimal.Parse(Session["TotalPrice"].ToString());
                OrderB2B_BUS.SaveOrderB2B(orderb2b, cart);
                if (Request.Cookies["Cart"] != null && !string.IsNullOrEmpty(Request.Cookies["Cart"].Value))
                {
                    Request.Cookies["Cart"].Expires = DateTime.Now.AddYears(-11);
                    Response.Cookies.Add(Request.Cookies["Cart"]);
                }
            }
            else
            {
                List<MyOrderProduct_Online> listmyorderproductonline = cart.GetList();

                HttpCookie cookie = new HttpCookie("Cart");

                string ctgiohang = "";
                for (int i = 0; i < listmyorderproductonline.Count; i++)
                {
                    if (i != listmyorderproductonline.Count - 1)
                    {
                        ctgiohang += listmyorderproductonline[i].ElectricDeviceID + ",";
                        ctgiohang += listmyorderproductonline[i].Quantity + "/";
                    }
                    else
                    {
                        ctgiohang += listmyorderproductonline[i].ElectricDeviceID + ",";
                        ctgiohang += listmyorderproductonline[i].Quantity;
                    }
                }
                Session["Flag"] = 1;
                cookie.Value = ctgiohang;
                cookie.Expires = DateTime.Now.AddMonths(1);
                Response.Cookies.Add(cookie);
            }
            Label1.Text = "Đã lưu lại giỏ hàng cho bạn trong lần sau";
            Label1.Visible = true;
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Cart cart = (Cart)Session["Cart"];
            

            if (Session["Role"].ToString() == "Đối tác doanh nghiệp")
            {
                string OrderB2B_ID = "";

                OrderB2B_BUS.GetOrderID(int.Parse(Session["UserID"].ToString()),ref OrderB2B_ID);
                OrderB2B_BUS.DeleteCart(OrderB2B_ID);
                if (Request.Cookies["Cart"] != null && !string.IsNullOrEmpty(Request.Cookies["Cart"].Value))
                {
                    Request.Cookies["Cart"].Expires = DateTime.Now.AddYears(-11);
                    Response.Cookies.Add(Request.Cookies["Cart"]);
                }
            }
            else
            {
                
                if (Request.Cookies["Cart"] != null && !string.IsNullOrEmpty(Request.Cookies["Cart"].Value))
                {
                    Request.Cookies["Cart"].Expires = DateTime.Now.AddYears(-11);
                    Response.Cookies.Add(Request.Cookies["Cart"]);
                }
            }
            Session["Cart"] = new Cart();

            gvdetailorderproduct.DataSource = null;
            gvdetailorderproduct.DataBind();

            Session["TongTien"] = 0;
            lbthanhtien.Text = Session["TongTien"].ToString();
            Label1.Text = "Đã hủy quá trình đặt sản phẩm của bạn";
            Label1.Visible = true;
        }

        protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
        {
            //button thanh toan
            Cart cart = (Cart)Session["Cart"];

            if (Session["UserID"] != "")
            {
                ORDER_B2B orderb2b = new ORDER_B2B();
                orderb2b.UserID = int.Parse(Session["UserID"].ToString());
                orderb2b.OrderedDate = DateTime.Now;
                orderb2b.TotalPrice = decimal.Parse(Session["TotalPrice"].ToString());
                OrderB2B_BUS.SaveOrderB2B(orderb2b, cart);

                //chuyen ve trang thuc hien quy trinh thanh toan
                Response.Redirect("~/Customer/ThanhToan_Buoc1_SendMail.aspx");
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }
        }
    }
}
